package com.vhall.component.service.account.impl;

import com.vhall.component.framework.common.utils.StringUtils;
import com.vhall.component.framework.common.utils.TimeUtil;
import com.vhall.component.plugin.common.manager.CommonCacheManager;
import com.vhall.component.plugin.common.thrift.common.UserTicketWrapper;
import com.vhall.component.plugin.common.thrift.common.WebUserTicket;
import com.vhall.component.service.account.UserTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yuanzh
 */
@Service
public class UserTicketServiceImpl implements UserTicketService {

    @Autowired
    private CommonCacheManager commonCacheManager;

    @Override
    public UserTicketWrapper createUserTicket(long userId) {
        String a1 = StringUtils.getRandom(16);
        String c2 = StringUtils.getRandom(20);
        String c3 = StringUtils.getRandom(20);
        String c3Key = StringUtils.getRandom(16);
        String c3Iv = StringUtils.getRandom(16);

        int expireHour = 24;

        long expireIn = expireHour * 60 * 60 * 1000L;
        long currentTimeMillis = System.currentTimeMillis();
        long expireTs = currentTimeMillis + expireIn;

        UserTicketWrapper userTicketWrapper = new UserTicketWrapper();
        WebUserTicket webUserTicket = new WebUserTicket();
        webUserTicket.setC2(c2);
        webUserTicket.setC3(c3);
        webUserTicket.setC3Key(c3Key);
        webUserTicket.setC3Iv(c3Iv);
        webUserTicket.setExpireTs(expireTs);

        userTicketWrapper.setCreateTs(TimeUtil.getSecondsFromMills(currentTimeMillis));
        userTicketWrapper.setA1(a1);
        userTicketWrapper.setUserId(userId);
        userTicketWrapper.setWebTicket(webUserTicket);
        if (commonCacheManager.saveUserTicket(userTicketWrapper, expireHour)) {
            return userTicketWrapper;
        }
        return null;
    }

}
